package com.touchfired.common.http;

import com.alibaba.fastjson.JSONObject;
import com.touchfired.common.http.response.Msg;
import com.touchfired.common.http.response.MsgUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@EnableWebMvc
@Configuration
@RestControllerAdvice(basePackages = "com.touchfired")
public class ResponseBodyConfig implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof Msg) {
            return o;
        }
        Msg<Object> result = MsgUtil.success(o);
        if (o instanceof String) {
            return JSONObject.toJSONString(result);
        }
        return result;
    }

}
